<?php
namespace app\admin\controller;

use app\admin\model\MenuList;
use app\admin\model\SystemConfig;
use cate_tree\CateTree;
use think\Db;
use think\Log;

class System extends UserAuth{

    /**
     * 系统管理
     * @author 王柯 <wangke.email@foxmail.com>
     * @return void
     */
    public function index(){

    }

    /**
     * 菜单栏目列表
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function menu_list(){
        $cate = new CateTree();

        $cateResult = Db('menu_list')
            ->select();

        $list = $cate
            ->create_tree($cateResult);
       // halt($list);
        /*$list = Db::name('menu_list')
            ->field("*,concat(path,id) as paths")
            ->order('paths desc')
            ->select();*/
        $this->assign('list',$list);
        return $this->fetch('menu_list');
    }
    /**
     * icon图标显示页面
     * @author 王柯 <wangke.email@foxmail.com>
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
     */
    public function icon(){
        return view('icon');
    }
    /**
     * 新增菜单栏目
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed|\think\response\Json
     */
    public function add_menu_list(){

        /*$list = Db::name('menu_list')
            ->field('id,list_name,level')
            //->where('level!=2')
            ->select();*/

        $cate = new CateTree();

        $cateResult = Db('menu_list')
            ->select();

        $list = $cate
            ->create_tree($cateResult);

        if(request()->isAjax()){
            $data = $_POST;
            if(!isset($data['module'])){
                return show(config('code.error'),'栏目模块名称不能为空！');
            }

            if(!isset($data['controller'])){
                return show(config('code.error'),'栏目控制器名称不能为空！');
            }

            if(!isset($data['function'])){
                return show(config('code.error'),'栏目方法名称不能为空！');
            }

            $data['frame_url'] = $data['module'].'/'.$data['controller'].'/'.$data['function'];

            //验证
            $validate = validate('menu_list');
            if(!$validate->scene('add_menu_list')->check($data)){
                return show(config('code.error'),$validate->getError());
            }
           // dump($data);die;
            $menu_list = new MenuList();
            if($data['pid'] == 0){
                $data['list_select_icon'] = '&#xe6d5;';

                $add = $menu_list
                    ->insert($data);
                if($add){
                    $path['path'] = $data['pid'] . ',' . $menu_list->getLastInsID();
                    $path['level'] = 1;
                    $res = $menu_list
                        ->where('id='.$menu_list->getLastInsID())
                        ->update($path);
                    if($res){
                        return show(config('code.success'),'新增成功！');
                    }else{
                        return show(config('code.error'),'新增失败！');
                    }
                }else{
                    return show(config('code.error'),'新增失败！');
                }
            }else if($data['pid'] != 0){
                $path = Db::name('menu_list')
                    ->where('id='.$data['pid'])
                    ->field('id,path')
                    ->find();
                $data['path'] = $path['path'];
                $data['level'] = substr_count($path['path'],',');
                $re = $menu_list
                    ->insert($data);
                if($re){
                    $path['id'] = $menu_list->getLastInsID();
                    $path['path'] = $data['path'] . ',' . $path['id'];
                    $path['level'] = substr_count($path['path'],',');
                    $res = $menu_list
                        ->where('id='.$path['id'])
                        ->update($path);
                    if($res){
                        return show(config('code.success'),'新增成功！');
                    }else{
                        return show(config('code.error'),'新增失败！');
                    }
                }else{
                    return show(config('code.error'),'新增失败！');
                }
            }
        }
        $this->assign('list',$list);
        return $this->fetch('add_menu_list');
    }

    /**
     * 修改菜单栏目
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed|\think\response\Json
     */
    public function edit_menu_list($id){
        $list = Db::name('menu_list')->where('id='.$id)->find();

        $list['_icon'] = htmlspecialchars($list['list_icon']);

        //查询子集栏目
        $menu = Db::name('menu_list')->where('pid='.$id)->find();

        /*$listTree = Db::name('menu_list')
            ->field("*,concat(path,id) as paths")
            //->where('level !=2')
            ->order('paths desc')
            ->select();*/

        $cate = new CateTree();

        $cateResult = Db('menu_list')
            ->select();

        $listTree = $cate
            ->create_tree($cateResult);

        if(request()->isAjax()){
            $data = $_GET;

            if(!isset($data['module'])){
                return show(config('code.error'),'栏目模块名称不能为空！');
            }

            if(!isset($data['controller'])){
                return show(config('code.error'),'栏目控制器名称不能为空！');
            }

            if(!isset($data['function'])){
                return show(config('code.error'),'栏目方法名称不能为空！');
            }

            $data['frame_url'] = $data['module'].'/'.$data['controller'].'/'.$data['function'];

            //验证
            $validate = validate('menu_list');
            if(!$validate->scene('edit_menu_list')->check($data)){
                return show(config('code.error'),$validate->getError());
            }

            $men = new MenuList();
            if($data['pid'] == 0){
                $data['level'] = 1;
                $data['list_select_icon'] = '&#xe6d5;';
                $data['path'] = $data['pid'] . ',' . $data['id'];
                $res = $men->where('id='.$data['id'])->update($data);

                if($res){
                    return show(config('code.success'),'修改成功！');
                }else{
                    return show(config('code.error'),'修改失败！');
                }
            }else{
                //判断修改顶级目录到其他目录目录下当前目录下是否有子集栏目
                if(!empty($menu)){
                    return show(config('code.error'),'该目录下还有子集栏目不能添加到其他栏目！');
                }

                $path = Db::name('menu_list')->where('id='.$data['pid'])->field('path,level')->find();

                $data['level'] = $path['level'] + 1;
                $data['path'] = $path['path'] . ',' . $data['id'];
                $data['list_select_icon'] = '&#xe6d5;';
                $res = $men
                    ->where('id='.$data['id'])
                    ->update($data);
                if($res){
                    return show(config('code.success'),'修改成功！');
                }else{
                    return show(config('code.error'),'修改失败！');
                }
            }
        }
        $this->assign([
            'listTree'=>$listTree,
            'list'=>$list,
        ]);
        return $this->fetch('edit_menu_list');
    }

    /**
     * 删除菜单栏目
     * @author 王柯 <25076778@qq.com>
     * @return \think\response\Json
     */
    public function del_menu_list(){
        $menu = new MenuList();
        $data = Db::name('menu_list')
            ->where('pid='.$_GET['id'])
            ->find();
        if(empty($data)){
            $result = $menu
                ->where('id='.$_GET['id'])
                ->delete();
            if($result){
                return show(config('code.success'),'删除成功！');
            }else{
                return show(config('code.error'),'删除失败！');
            }
        }else{
            return show(config('code.error'),'该目录下还有子集目录不能删除！');
        }
    }

    /**
     * 系统配置列表
     * @author 王柯 <wangke.email@foxmail.com>
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
     */
    public function config_list(){
        $m = new SystemConfig();
        $list = $m->getAll();
        $count = $m->getCount();
        $this->assign([
            'list' => $list,
            'count' => $count,
        ]);
        return view('config_list');
    }

    /**
     * 添加系统配置
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|string|\think\response\Json|\think\response\View
     */
    public function add_config(){
        //系统配置菜单栏目
        $list = config('system.system_config');
        if(request()->isAjax()){
            $data = $_POST;
            //验证
            $validate = validate('system_config');
            if(!$validate->scene('add_config')->check($data)){
                return show(config('code.error'),$validate->getError());
            }

            $res = Db::name('system_config')->insert($data);
            if($res){
                return show(config('code.success'),'添加成功！');
            }else{
                return show(config('code.error'),'添加失败！');
            }
        }

        $this->assign('list',$list);
        return view('add_config');
    }

    /**
     * 修改配置信息
     * @param int id 配置id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|string|\think\response\Json|\think\response\View
     */
    public function edit_config($id){
        $conf = Db::name('system_config')->where('id='.$id)->find();

        //系统配置菜单栏目
        $list = config('system.system_config');

        if(request()->isAjax()){
            $data = $_POST;
            //验证
            $validate = validate('system_config');
            if(!$validate->scene('edit_config')->check($data)){
                return show(config('code.error'),$validate->getError());
            }

            $res = Db::name('system_config')
                ->where('id='.$data['id'])
                ->update($data);
            if($res){
                return show(config('code.success'),'修改成功！');
            }else{
                return show(config('code.error'),'修改失败！');
            }
        }

        $this->assign([
            'conf' => $conf,
            'list' => $list,
        ]);
        return view('edit_config');
    }

    /**
     * 删除配置信息
     * @param int id 配置id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function del_config(){
        $result = Db::name('system_config')
            ->where('id='.$_GET['id'])
            ->delete();
        if($result){
            return show(config('code.success'),'删除成功！');
        }else{
            return show(config('code.error'),'删除失败！');
        }
    }

    /**
     * 批量删除配置信息
     * @param array id 配置id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function batch_del_config(){
        $data = $_POST;
        if(!isset($data['id'])){
            return show(config('code.error'),'id is not found！',[],404);
        }

        $str = implode(',',$data['id']);
        $del = Db::name('system_config')
            ->where("id in($str)")
            ->delete();
        if($del){
            return show(config('code.success'),'批量删除成功！');
        }else{
            return show(config('code.error'),'批量删除失败！');
        }
    }

    /**
     * 系统配置
     * @author 王柯 <wangke.email@foxmail.com>
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
     */
    public function system_config(){
        //系统配置项
        $list = Db::name('system_config')->select();

        //系统菜单栏目
        $system_menu = config('system.system_config');

        if(request()->isAjax()){
            $data = input('post.');

            try{
                //附件类型数据处理
                $imgColumn = db('system_config')->where('config_type',6)->column('en_name');

                foreach ($imgColumn as $k => $v) {
                    if(!empty($_FILES)){

                        $images = uploadImage($v);
                        if(is_object($images)){
                            return $images;
                        }else{
                            $data[$v] = $images;
                        }
                    }else{
                        unset($data[$v]);
                    }
                }

                foreach ($data as $k => $v) {
                    if(is_array($v)){
                        $data[$k] = implode(',', $v);
                    }
                }

                foreach ($data as $k => $v) {
                    db('system_config')->where('en_name',$k)->update(['default_value'=>trim($v)]);
                }

                //更新配置信息
                systemConfig('',true);

                return show(config('code.success'),'保存配置成功！');

            }catch (\Exception $e){
                Log::write($e->getMessage());
                return show(config('code.error'),'保存配置失败！');
            }
        }

        $this->assign([
            'list' => $list,
            'system_menu' => $system_menu,
        ]);

        return view('system_config');
    }
}
